package com.ybg.bookmanages.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ybg.bookcommons.dto.ReturnDTO;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.converter.json.GsonBuilderUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
@Component
public class TokenerInterceptor implements HandlerInterceptor {
  private StringRedisTemplate template;
  public TokenerInterceptor(StringRedisTemplate srt) {
    this.template = srt;
  }
  @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
    ObjectMapper om = new ObjectMapper();
    //1.获取请求头Authorization的值
    String auth = request.getHeader("Authorization");
    //2.无法获取token token为null 说明用户尚未登陆
    if (auth== null){
      //准备提示前端用户 发生错误
      response.setCharacterEncoding("utf-8");
      PrintWriter out = response.getWriter();
      ReturnDTO retdto = ReturnDTO.builder().status("fail").message("用户尚未登录").build();
      out.write(om.writeValueAsString(retdto));
      out.flush();
      out.close();
      return false;
    }
    //3.用户有令牌但是超期限 结果有问题
    String res = template.opsForValue().get(auth);
    if (res == null){
      //准备提示前端用户 发生错误
      response.setCharacterEncoding("utf-8");
      PrintWriter out = response.getWriter();
      ReturnDTO retdto = ReturnDTO.builder().status("fail").message("用户登录超时，请重新登录").build();
      out.write(om.writeValueAsString(retdto));
      out.flush();
      out.close();
      return false;
    }
    return true;
    }

}
